package com.fang.task;

import com.fang.entity.Cat;
import com.fang.utils.TaskProcessUtil;
import com.google.common.collect.Lists;
import lombok.SneakyThrows;
import org.checkerframework.checker.units.qual.C;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author Fang Ruichuan
 * @date 2022-09-30 16:34
 */
public class ChildTask {
    private final int POOL_SIZE = 3;
    private final int SPLIT_SIZE = 4;
    private String taskName;

    // 接收JVM关闭信号，实现优雅停机
    protected volatile boolean terminal = false;

    public ChildTask(String taskName) {
        this.taskName = taskName;
    }

    // 优雅停机
    public void terminal() {
        terminal = true;
        System.out.println(taskName + " shutDown");
    }

    // 程序执行入口
    public void doExecute() {
        int i = 0;
        while (Boolean.TRUE) {
            System.out.println(taskName + ":Cycle-" + i + "-Begin");
            // 获取数据
            List<Cat> datas = queryData();
            // 处理数据
            taskExecute(datas);
            System.out.println(taskName + ":Cycle-" + i + "-End");
            if (terminal) {
                // 只有应用关闭，才会走到这里，用于实现优雅的下线
                break;
            }
            i++;
        }
        TaskProcessUtil.releaseExecutors(taskName);
    }

    // 处理单个任务数据
    private void taskExecute(List<Cat> sourceDatas) {
        if (CollectionUtils.isEmpty(sourceDatas)) {
            return;
        }
        // 将数据拆成4份
        List<List<Cat>> splitDatas = Lists.partition(sourceDatas, SPLIT_SIZE);
        final CountDownLatch latch = new CountDownLatch(splitDatas.size());
        // 并发处理拆分的数据，公用一个线程池
        splitDatas.forEach(datas -> {
            ExecutorService executorService = TaskProcessUtil.getOrInitExecutors(taskName, POOL_SIZE);
            executorService.submit(() -> {
                doProcessData(datas, latch);
            });
        });
        try {
            latch.wait();
        } catch (InterruptedException e) {
            System.out.println(e.getStackTrace());
        }
    }

    // 处理数据
    private void doProcessData(List<Cat> datas, CountDownLatch latch) {
        try {
            for (Cat cat : datas) {
                System.out.println(taskName + ":" + cat.toString() + ",ThreadName:" + Thread.currentThread().getName());
                TimeUnit.MILLISECONDS.sleep(1000L);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (Objects.nonNull(latch)) {
                latch.countDown();
            }
        }
    }

    // 获取永东任务数据
    private List<Cat> queryData() {
        Cat[] datas = new Cat[5];
        for (int i = 0; i < 5; i++) {
            datas[i] = Cat.builder().catName("罗小黑" + i).build();
        }
        return Arrays.asList(datas);
    }
}
